# pgdb.py

import psycopg2
from config import DATABASE_CONFIG


def get_connection():
    """创建并返回数据库连接"""
    conn = psycopg2.connect(**DATABASE_CONFIG)
    return conn


def get_cursor(conn):
    """创建并返回游标对象"""
    return conn.cursor()


def close_connection(conn, cursor):
    """关闭游标和连接"""
    if cursor is not None:
        cursor.close()
    if conn is not None:
        conn.close()


def execute_query(query, params=None, fetch=False):
    """
    执行数据库查询并处理事务。
    :param query: 要执行的SQL查询
    :param params: 查询参数
    :param fetch: 是否需要获取查询结果
    :return: (success, result) 元组，success 表示操作是否成功，result 表示查询结果或错误消息
    """
    conn = get_connection()
    cursor = get_cursor(conn)

    try:
        cursor.execute(query, params)
        if fetch:
            result = cursor.fetchall()
        else:
            result = None
        conn.commit()
        return True, result
    except Exception as e:
        conn.rollback()
        return False, str(e)
    finally:
        close_connection(conn, cursor)

# 使用示例
# from db import execute_query
#
#
# def fetch_data():
#     query = "SELECT * FROM your_table"
#     success, result = execute_query(query, fetch=True)
#
#     if success:
#         for row in result:
#             print(row)
#     else:
#         print(f"Failed to fetch data: {result}")
